package com.easylinkin.sm.context;

import static site.morn.framework.context.CommonConstant.Caches.ROLES;

import com.easylinkin.sm.entity.Role;
import com.easylinkin.sm.entity.User;
import com.easylinkin.sm.service.RoleService;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import site.morn.bean.annotation.Target;
import site.morn.cache.CacheGroup;
import site.morn.framework.context.AccountContext;
import site.morn.framework.context.RolesContextProducer;

/**
 * 获取当前角色
 *
 * @author TianGanLin
 * @since 1.2.1, 2019/9/12
 */
@Component
@Target(Role.class)
public class SmRolesContextProducer implements RolesContextProducer<Role> {

  @Resource
  private RoleService roleService;

  @Override
  public Collection<Role> getCurrent() {
    User user = AccountContext.currentUser();
    if (Objects.isNull(user)) {
      return Collections.emptyList();
    }
    CacheGroup cacheGroup = AccountContext.cacheGroup();
    return cacheGroup.get(ROLES, user.getUsername(), () -> get(user.getId()));
  }

  /**
   * 获取角色信息
   *
   * @param userId 用户编号
   * @return 角色集合
   */
  private Collection<Role> get(Long userId) {
    return roleService.getByUserId(userId);
  }
}
